package com.softeem.yqst_server.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.softeem.yqst_server.dto.Result;
import com.softeem.yqst_server.enity.Admin;
import com.softeem.yqst_server.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Wrapper;

@RequestMapping("/admin")
@RestController
public class AdminController {

    @Autowired
    private AdminService adminService;


    /**
     * 根据输入的管理员账号和密码实现登录接口
     */
    @RequestMapping("login")
    public Result login(String username, String password) {
        Admin admin = adminService.getOne(Wrappers.<Admin>lambdaQuery().eq(Admin::getUsername, username));
        if (admin != null && admin.getPassword().equals(password)){
            return Result.ok().setMsg("登录成功").setData(admin);

        }
        return Result.fail().setMsg("账号或密码错误");
    }

    /**
     * 实现管理员注册接口。该方法接受一个用户名和密码，检查该用户是否已存在
     */
    @RequestMapping("/register")
    public Result register(String username, String password) {
        // 通过用户名查询是否存在该管理员账号
        Admin admin = adminService.getOne(Wrappers.<Admin>lambdaQuery().eq(Admin::getUsername, username));
        if (admin == null) {
            // 如果管理员账号不存在，则创建新账号并保存
            Admin admin1 = new Admin();
            admin1.setUsername(username);
            admin1.setPassword(password);
            adminService.save(admin1);
            return Result.ok().setMsg("注册成功").setData(admin1);
        }
        // 如果管理员账号已存在，则返回注册失败
        return Result.fail().setMsg("账号已存在");
    }
}

